﻿Public Class Maps
    Inherits System.Web.UI.Page

    Protected Enum enmScreenMode As Integer

        Add = 1
        Edit = 2

    End Enum

    Protected Property ScreenMode As enmScreenMode

        Get

            If ViewState("ScreenMode") Is Nothing Then

                ViewState("ScreenMode") = enmScreenMode.Add

            End If

            Return ViewState("ScreenMode")

        End Get

        Set(value As enmScreenMode)

            ViewState("ScreenMode") = value

        End Set

    End Property

    Protected Property CurrentRecord As ObjectId

        Get

            If ViewState("CurrentRecord") Is Nothing Then

                ViewState("CurrentRecord") = ObjectId.Empty

            End If

            Return ViewState("CurrentRecord")

        End Get

        Set(value As ObjectId)

            ViewState("CurrentRecord") = value

        End Set

    End Property

    Protected Property CurrentTerritoryRecord As ObjectId

        Get

            If ViewState("CurrentTerritoryRecord") Is Nothing Then

                ViewState("CurrentTerritoryRecord") = ObjectId.Empty

            End If

            Return ViewState("CurrentTerritoryRecord")

        End Get

        Set(value As ObjectId)

            ViewState("CurrentTerritoryRecord") = value

        End Set

    End Property

    Protected Property CurrentMapGroupRecord As ObjectId

        Get

            If ViewState("CurrentMapGroupRecord") Is Nothing Then

                ViewState("CurrentMapGroupRecord") = ObjectId.Empty

            End If

            Return ViewState("CurrentMapGroupRecord")

        End Get

        Set(value As ObjectId)

            ViewState("CurrentMapGroupRecord") = value

        End Set

    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Try

            If Not IsPostBack Then

                'Populate the dropdown list with default values
                cboMaxUsers.DataSource = modShared.mlintPlayerCount
                cboMaxUsers.DataBind()

                BindGrid()

                If Not HttpContext.Current.Session("MapID") Is Nothing Then

                    Me.CurrentRecord = HttpContext.Current.Session("MapID")
                    HttpContext.Current.Session("MapID") = Nothing

                    LoadRecord()

                    Me.ScreenMode = enmScreenMode.Edit

                End If

            End If

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub BindGrid()

        Dim mcMapCursor As MongoCursor = Nothing

        Try
            'get all active maps from database
            mcMapCursor = DatabaseCalls.GetAllMaps()

            lvMaps.DataSource = mcMapCursor
            lvMaps.DataBind()

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub BindTerritories()

        Dim mcTerritoryCursor As MongoCursor = Nothing

        Try

            'get all active territories from database
            mcTerritoryCursor = DatabaseCalls.GetAllTerritories(Me.CurrentRecord)

            'Bind to GridView
            lvTerritories.DataSource = mcTerritoryCursor
            lvTerritories.DataBind()

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub BindMapGroups()

        Dim mcMapGroupCursor As MongoCursor = Nothing

        Try

            'get all active Groups from database
            mcMapGroupCursor = DatabaseCalls.GetAllMapGroups(Me.CurrentRecord)

            'Bind to GridView
            lvMapGroups.DataSource = mcMapGroupCursor
            lvMapGroups.DataBind()

        Catch ex As Exception

        End Try

    End Sub

    Private Sub cmdSave_Click(sender As Object, e As System.EventArgs) Handles cmdSave.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcMaps As MongoCollection(Of Trebuchet.Map) = Nothing
        Dim mcMapCursor As MongoCursor = Nothing
        Dim mMap As Trebuchet.Map = Nothing
        Dim bolSave As Boolean = True

        Try

            'Validate Page Data
            ValidateData(bolSave)

            If bolSave Then

                'Check to see if the Name or FilePath already exists in the system
                mdDatabase = DBHelper.GetDataBase()
                mcMaps = mdDatabase.GetCollection(Of Trebuchet.Map)("Maps")

                mcMapCursor = mcMaps.FindAs(Of Trebuchet.Map)(Query.And(Query.And(Query.EQ("Name", txtName.Text.Trim), Query.EQ("FileName", txtFileName.Text.Trim))))

                If Not mcMapCursor Is Nothing _
                    AndAlso mcMapCursor.Count > 0 Then

                    If mcMapCursor(0)._id <> Me.CurrentRecord Then

                        bolSave = False

                    End If

                End If

                If bolSave Then

                    If Me.CurrentRecord = ObjectId.Empty Then

                        'Save new record
                        mMap = New Trebuchet.Map

                        mMap.Name = txtName.Text.Trim
                        mMap.Description = txtDescription.Text.Trim
                        mMap.FileName = txtFileName.Text.Trim
                        mMap.MaxUsers = cboMaxUsers.SelectedValue
                        mMap.BonusDivider = txtBonusDivider.Text.Trim

                    Else

                        'Update existing record.
                        mMap = DatabaseCalls.GetMapByID(Me.CurrentRecord)

                        mMap.Name = txtName.Text.Trim
                        mMap.Description = txtDescription.Text.Trim
                        mMap.FileName = txtFileName.Text.Trim
                        mMap.MaxUsers = cboMaxUsers.SelectedValue
                        mMap.BonusDivider = txtBonusDivider.Text.Trim

                    End If

                    mcMaps.Save(mMap)

                    Me.CurrentRecord = mMap._id
                    LoadRecord()
                    Me.ScreenMode = enmScreenMode.Edit

                End If

            End If

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub ValidateData(ByRef bolValid As Boolean)

        Try

            If txtName.Text.Trim = "" Then

                bolValid = False

                'Display Message

            End If

            If txtFileName.Text.Trim = "" Then

                bolValid = False

                'Display Message

            End If

            If txtBonusDivider.Text.Trim = "" AndAlso Integer.TryParse(txtBonusDivider.Text.Trim, 0) Then

                bolValid = False

                'Display Message

            End If

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub LoadRecord()

        Dim mMap As Trebuchet.Map = Nothing

        Try

            mMap = DatabaseCalls.GetMapByID(Me.CurrentRecord)

            txtName.Text = mMap.Name
            txtDescription.Text = mMap.Description
            txtFileName.Text = mMap.FileName
            txtBonusDivider.Text = mMap.BonusDivider
            cboMaxUsers.SelectedValue = mMap.MaxUsers

            BindTerritories()
            BindMapGroups()

        Catch ex As Exception

        End Try

    End Sub

    Private Sub lvMaps_ItemCommand(sender As Object, e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles lvMaps.ItemCommand

        Try

            Select Case e.CommandName.ToUpper

                Case "EDITRECORD"
                    'Load the record into the page, set screen mode

                    Me.CurrentRecord = ObjectId.Parse(e.CommandArgument)

                    LoadRecord()

                    Me.ScreenMode = enmScreenMode.Edit

            End Select


        Catch ex As Exception

        End Try

    End Sub

    Private Sub lvMaps_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvMaps.ItemDataBound

        Try

            If e.Item.ItemType = ListViewItemType.DataItem Then

                CType(e.Item.FindControl("litName"), System.Web.UI.WebControls.Literal).Text = e.Item.DataItem.Name
                CType(e.Item.FindControl("litDesc"), System.Web.UI.WebControls.Literal).Text = e.Item.DataItem.Description
                CType(e.Item.FindControl("litFileName"), System.Web.UI.WebControls.Literal).Text = e.Item.DataItem.FileName
                CType(e.Item.FindControl("litMaxUsers"), System.Web.UI.WebControls.Literal).Text = e.Item.DataItem.MaxUsers
                CType(e.Item.FindControl("litBonusDivider"), System.Web.UI.WebControls.Literal).Text = e.Item.DataItem.BonusDivider
                CType(e.Item.FindControl("cmdEdit"), System.Web.UI.WebControls.ImageButton).CommandArgument = e.Item.DataItem._id.ToString

            End If

        Catch ex As Exception

        End Try

    End Sub

    Private Sub Maps_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender

        Try

            Select Case ScreenMode

                Case enmScreenMode.Add

                    cmdDelete.Visible = False
                    cmdCancel.Visible = False
                    cmdSave.Visible = True
                    cmdExit.Visible = True

                    lvMaps.Visible = True
                    fsTerritories.Visible = False
                    fsMapGroups.Visible = False

                Case enmScreenMode.Edit

                    cmdDelete.Visible = True
                    cmdCancel.Visible = True
                    cmdSave.Visible = True
                    cmdExit.Visible = False

                    lvMaps.Visible = False
                    fsTerritories.Visible = True
                    fsMapGroups.Visible = True

            End Select

        Catch ex As Exception

        End Try

    End Sub

    Private Sub cmdCancel_Click(sender As Object, e As System.EventArgs) Handles cmdCancel.Click

        Try

            Me.CurrentRecord = Nothing

            ClearAllControls(FormControls)

            BindGrid()

            Me.ScreenMode = enmScreenMode.Add

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub ClearAllControls(ByVal objControl As Object)

        Try

            For Each Control In objControl.Controls

                If TypeOf Control Is TextBox Then

                    Control.Text = ""

                End If

                If TypeOf Control Is DropDownList Then

                    Control.SelectedIndex = 0

                End If

            Next

        Catch ex As Exception

        End Try

    End Sub

    Private Sub cmdDelete_Click(sender As Object, e As System.EventArgs) Handles cmdDelete.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcMaps As MongoCollection(Of Trebuchet.Map) = Nothing
        Dim mcTerritories As MongoCollection(Of Trebuchet.Territory) = Nothing
        Dim mcTerritoriesCursor As MongoCursor(Of Trebuchet.Territory) = Nothing
        Dim tTerritory As Trebuchet.Territory = Nothing
        Dim mcTerritoriesXREF As MongoCollection(Of Trebuchet.TerritoryTerritoryXREF) = Nothing
        Dim mcMapGroups As MongoCollection(Of Trebuchet.MapGroup) = Nothing
        Dim mcMapGroupsCursor As MongoCursor(Of Trebuchet.MapGroup) = Nothing
        Dim mgMapGroup As Trebuchet.MapGroup = Nothing
        Dim mcMapGroupXREF As MongoCollection(Of Trebuchet.MapGroupTerritoryXREF) = Nothing

        Try

            mdDatabase = DBHelper.GetDataBase
            mcMaps = mdDatabase.GetCollection(Of Trebuchet.Map)("Maps")
            mcTerritories = mdDatabase.GetCollection(Of Trebuchet.Territory)("Territories")
            mcTerritoriesXREF = mdDatabase.GetCollection(Of Trebuchet.TerritoryTerritoryXREF)("TerritoryTerritoryXREF")
            mcMapGroups = mdDatabase.GetCollection(Of Trebuchet.MapGroup)("MapGroups")
            mcMapGroupXREF = mdDatabase.GetCollection(Of Trebuchet.MapGroupTerritoryXREF)("MapGroupTerritoryXREF")

            mcMaps.Remove(Query.EQ("_id", Me.CurrentRecord))

            'Remove all child controls
            'Territories, groups, xrefs
            mcTerritoriesCursor = mcTerritories.FindAs(Of Trebuchet.Territory)(Query.EQ("Map_id", Me.CurrentRecord))
            mcMapGroupsCursor = mcMapGroups.FindAs(Of Trebuchet.MapGroup)(Query.EQ("Map_id", Me.CurrentRecord))

            For Each tTerritory In mcTerritoriesCursor

                mcTerritoriesXREF.Remove(Query.Or(Query.EQ("FromTerritory_id", tTerritory._id), Query.EQ("ToTerritory_id", tTerritory._id)))
                mcMapGroupXREF.Remove(Query.EQ("Territory_id", tTerritory._id))
                mcTerritories.Remove(Query.EQ("_id", tTerritory._id))

            Next

            For Each mgMapGroup In mcMapGroupsCursor

                mcMapGroupXREF.Remove(Query.EQ("MapGroup_id", mgMapGroup._id))
                mcMapGroups.Remove(Query.EQ("_id", mgMapGroup._id))

            Next

            ClearAllControls(FormControls)

            BindGrid()

            Me.ScreenMode = enmScreenMode.Add

        Catch ex As Exception

        End Try

    End Sub

    Private Sub cmdAddTerritory_Click(sender As Object, e As System.EventArgs) Handles cmdAddTerritory.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcTerritories As MongoCollection(Of Trebuchet.Territory) = Nothing
        Dim mcTerritoryCursor As MongoCursor = Nothing
        Dim mTerritory As Trebuchet.Territory = Nothing
        Dim bolSave As Boolean = True

        Try

            'Validate Page Data
            ValidateTerritoryData(bolSave)

            If bolSave Then

                'Check to see if the SVGID already exists
                mdDatabase = DBHelper.GetDataBase()
                mcTerritories = mdDatabase.GetCollection(Of Trebuchet.Territory)("Territories")

                mcTerritoryCursor = mcTerritories.FindAs(Of Trebuchet.Territory)(Query.And(Query.EQ("SVGID", txtSVGID.Text.Trim)))

                If mcTerritoryCursor.Count > 0 Then

                    bolSave = False

                    'Display Mesage of unique fail

                End If

                If bolSave Then

                    'Save new record
                    mTerritory = New Trebuchet.Territory

                    mTerritory.Name = txtTerritoryName.Text.Trim
                    mTerritory.SVGID = txtSVGID.Text.Trim
                    mTerritory.Map_id = Me.CurrentRecord
                    mTerritory.MaxUnits = txtMaxUnits.Text.Trim

                    mcTerritories.Save(mTerritory)

                End If

                BindTerritories()

                ClearAllControls(divTerritoryAddControls)

            End If

        Catch

        End Try

    End Sub

    Protected Sub ValidateTerritoryData(ByRef bolValid As Boolean)

        Try

            If txtTerritoryName.Text.Trim = "" Then

                bolValid = False

                'Display Message

            End If

            If txtSVGID.Text.Trim = "" Then

                bolValid = False

                'Display Message

            End If

            If txtMaxUnits.Text.Trim = "" AndAlso Integer.TryParse(txtMaxUnits.Text.Trim, 0) Then

                bolValid = False

                'Display Message

            End If

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub ValidateModalTerritoryData(ByRef bolValid As Boolean)

        Try

            If txtModalTerritoryName.Text.Trim = "" Then

                bolValid = False

                'Display Message

            End If

            If txtModalSVGID.Text.Trim = "" Then

                bolValid = False

                'Display Message

            End If

            If txtModalMaxUnits.Text.Trim = "" AndAlso Integer.TryParse(txtModalMaxUnits.Text.Trim, 0) Then

                bolValid = False

                'Display Message

            End If

        Catch ex As Exception

        End Try

    End Sub

    Private Sub lvTerritories_ItemCommand(sender As Object, e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles lvTerritories.ItemCommand

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcTerritories As MongoCollection(Of Trebuchet.Territory) = Nothing
        Dim mcTerritoriesXREF As MongoCollection(Of Trebuchet.TerritoryTerritoryXREF) = Nothing
        Dim mcMapGroupXREF As MongoCollection(Of Trebuchet.MapGroupTerritoryXREF) = Nothing

        Try

            Select Case e.CommandName.ToUpper

                Case "EDITRECORD"
                    'Load the record into modal
                    Me.CurrentTerritoryRecord = ObjectId.Parse(e.CommandArgument)

                    mpeTerritoryEdit.Show()

                    LoadTerritoryModal()

                Case "DELETERECORD"

                    'Delete record
                    mdDatabase = DBHelper.GetDataBase()
                    mcTerritories = mdDatabase.GetCollection(Of Trebuchet.Territory)("Territories")
                    mcTerritoriesXREF = mdDatabase.GetCollection(Of Trebuchet.TerritoryTerritoryXREF)("TerritoryTerritoryXREF")
                    mcMapGroupXREF = mdDatabase.GetCollection(Of Trebuchet.MapGroupTerritoryXREF)("MapGroupTerritoryXREF")

                    mcTerritories.Remove(Query.EQ("_id", ObjectId.Parse(e.CommandArgument)))

                    'Remove related data
                    mcTerritoriesXREF.Remove(Query.Or(Query.EQ("FromTerritory_id", ObjectId.Parse(e.CommandArgument)), Query.EQ("ToTerritory_id", ObjectId.Parse(e.CommandArgument))))
                    mcMapGroupXREF.Remove(Query.EQ("Territory_id", ObjectId.Parse(e.CommandArgument)))

                    'Reload Grid
                    BindTerritories()

            End Select


        Catch ex As Exception

        End Try

    End Sub

    Private Sub lvTerritories_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvTerritories.ItemDataBound

        Try

            If e.Item.ItemType = ListViewItemType.DataItem Then

                CType(e.Item.FindControl("litName"), System.Web.UI.WebControls.Literal).Text = e.Item.DataItem.Name
                CType(e.Item.FindControl("litSVGID"), System.Web.UI.WebControls.Literal).Text = e.Item.DataItem.SVGID
                CType(e.Item.FindControl("litMaxUnits"), System.Web.UI.WebControls.Literal).Text = e.Item.DataItem.MaxUnits
                CType(e.Item.FindControl("cmdEdit"), System.Web.UI.WebControls.ImageButton).CommandArgument = e.Item.DataItem._id.ToString
                CType(e.Item.FindControl("cmdDelete"), System.Web.UI.WebControls.ImageButton).CommandArgument = e.Item.DataItem._id.ToString

            End If

        Catch ex As Exception

        End Try

    End Sub

    Private Sub cmdModalTerritorySave_Click(sender As Object, e As System.EventArgs) Handles cmdModalTerritorySave.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcTerritories As MongoCollection(Of Trebuchet.Territory) = Nothing
        Dim mcTerritoryCursor As MongoCursor = Nothing
        Dim mTerritory As Trebuchet.Territory = Nothing
        Dim bolSave As Boolean = True

        Try

            'Validate Page Data
            ValidateModalTerritoryData(bolSave)

            If bolSave Then

                'Check to see if the SVGID already exists
                mdDatabase = DBHelper.GetDataBase()
                mcTerritories = mdDatabase.GetCollection(Of Trebuchet.Territory)("Territories")

                mcTerritoryCursor = mcTerritories.FindAs(Of Trebuchet.Territory)(Query.And(Query.EQ("SVGID", txtModalSVGID.Text.Trim)))

                If Not mcTerritoryCursor Is Nothing _
                    AndAlso mcTerritoryCursor.Count > 0 Then

                    If mcTerritoryCursor(0)._id <> Me.CurrentTerritoryRecord Then

                        bolSave = False

                    End If

                End If

                If bolSave Then

                    'Update existing record.
                    mTerritory = DatabaseCalls.GetTerritoryByID(Me.CurrentTerritoryRecord)

                    mTerritory.Name = txtModalTerritoryName.Text.Trim
                    mTerritory.SVGID = txtModalSVGID.Text.Trim
                    mTerritory.Map_id = Me.CurrentRecord
                    mTerritory.MaxUnits = txtModalMaxUnits.Text.Trim

                    mcTerritories.Save(mTerritory)

                    'Add message to parent message display

                    Me.CurrentTerritoryRecord = Nothing
                    BindTerritories()
                    mpeTerritoryEdit.Hide()

                End If

            End If

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub LoadTerritoryModal()

        Dim mTerritory As Trebuchet.Territory = Nothing

        Try

            mTerritory = DatabaseCalls.GetTerritoryByID(Me.CurrentTerritoryRecord)

            txtModalTerritoryName.Text = mTerritory.Name
            txtModalSVGID.Text = mTerritory.SVGID
            txtModalMaxUnits.Text = mTerritory.MaxUnits

            LoadTerritoryXrefData()

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub LoadTerritoryXrefData()

        Dim mcrTerritoryXrefCursor As MongoCursor = Nothing
        Dim mcrTerritoryCursor As MongoCursor = Nothing
        Dim ttxItem As Trebuchet.Territory = Nothing
        Dim baArray As BsonArray = Nothing

        Try

            'get all data from database
            mcrTerritoryXrefCursor = DatabaseCalls.GetAllTerritoriesFromTerritoryTerritoryXrefByTerritoryID(Me.CurrentTerritoryRecord)

            baArray = New BsonArray()

            For Each ttxItem In mcrTerritoryXrefCursor

                baArray.Add(ttxItem._id)

            Next

            'Add current record to be removed
            baArray.Add(Me.CurrentTerritoryRecord)

            mcrTerritoryCursor = DatabaseCalls.GetAllNonSelectedTerritoriesForXref(baArray)

            lstSelectedTerritories.DataSource = mcrTerritoryXrefCursor
            lstSelectedTerritories.DataValueField = "_id"
            lstSelectedTerritories.DataTextField = "Name"
            lstSelectedTerritories.DataBind()

            lstAvailableTerritories.DataSource = mcrTerritoryCursor
            lstAvailableTerritories.DataValueField = "_id"
            lstAvailableTerritories.DataTextField = "Name"
            lstAvailableTerritories.DataBind()

        Catch ex As Exception


        End Try

    End Sub

    Private Sub cmdTerritoryIn_Click(sender As Object, e As System.EventArgs) Handles cmdTerritoryIn.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcTerritoryXref As MongoCollection(Of Trebuchet.TerritoryTerritoryXREF) = Nothing
        Dim liItem As ListItem = Nothing
        Dim txTerritoryXref As Trebuchet.TerritoryTerritoryXREF = Nothing

        Try

            mdDatabase = DBHelper.GetDataBase()
            mcTerritoryXref = mdDatabase.GetCollection(Of Trebuchet.TerritoryTerritoryXREF)("TerritoryTerritoryXref")

            For Each liItem In lstAvailableTerritories.Items

                If liItem.Selected Then

                    txTerritoryXref = New Trebuchet.TerritoryTerritoryXREF()

                    txTerritoryXref.FromTerritory_id = Me.CurrentTerritoryRecord
                    txTerritoryXref.ToTerritory_id = ObjectId.Parse(liItem.Value)

                    mcTerritoryXref.Save(txTerritoryXref)

                End If

            Next

            LoadTerritoryXrefData()

        Catch ex As Exception

        End Try

    End Sub

    Private Sub cmdTerritoryOut_Click(sender As Object, e As System.EventArgs) Handles cmdTerritoryOut.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcTerritoryXref As MongoCollection(Of Trebuchet.TerritoryTerritoryXREF) = Nothing
        Dim liItem As ListItem = Nothing
        Dim txTerritoryXref As Trebuchet.TerritoryTerritoryXREF = Nothing

        Try

            mdDatabase = DBHelper.GetDataBase()
            mcTerritoryXref = mdDatabase.GetCollection(Of Trebuchet.TerritoryTerritoryXREF)("TerritoryTerritoryXref")

            For Each liItem In lstSelectedTerritories.Items

                If liItem.Selected Then

                    mcTerritoryXref.Remove(Query.And(Query.EQ("FromTerritory_id", Me.CurrentTerritoryRecord), Query.EQ("ToTerritory_id", ObjectId.Parse(liItem.Value))))

                End If

            Next

            LoadTerritoryXrefData()

        Catch ex As Exception

        End Try

    End Sub

    Private Sub cmdAllTerritoryIn_Click(sender As Object, e As System.EventArgs) Handles cmdAllTerritoryIn.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcTerritoryXref As MongoCollection(Of Trebuchet.TerritoryTerritoryXREF) = Nothing
        Dim liItem As ListItem = Nothing
        Dim txTerritoryXref As Trebuchet.TerritoryTerritoryXREF = Nothing

        Try

            mdDatabase = DBHelper.GetDataBase()
            mcTerritoryXref = mdDatabase.GetCollection(Of Trebuchet.TerritoryTerritoryXREF)("TerritoryTerritoryXref")

            For Each liItem In lstAvailableTerritories.Items

                txTerritoryXref = New Trebuchet.TerritoryTerritoryXREF()

                txTerritoryXref.FromTerritory_id = Me.CurrentTerritoryRecord
                txTerritoryXref.ToTerritory_id = ObjectId.Parse(liItem.Value)

                mcTerritoryXref.Save(txTerritoryXref)

            Next

            LoadTerritoryXrefData()

        Catch ex As Exception

        End Try

    End Sub

    Private Sub cmdAllTerritoryOut_Click(sender As Object, e As System.EventArgs) Handles cmdAllTerritoryOut.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcTerritoryXref As MongoCollection(Of Trebuchet.TerritoryTerritoryXREF) = Nothing

        Try

            mdDatabase = DBHelper.GetDataBase()
            mcTerritoryXref = mdDatabase.GetCollection(Of Trebuchet.TerritoryTerritoryXREF)("TerritoryTerritoryXref")
            mcTerritoryXref.Remove(Query.EQ("FromTerritory_id", Me.CurrentTerritoryRecord))

            LoadTerritoryXrefData()

        Catch ex As Exception

        End Try

    End Sub

    Private Sub cmdAddMapGroup_Click(sender As Object, e As System.EventArgs) Handles cmdAddMapGroup.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcMapGroups As MongoCollection(Of Trebuchet.MapGroup) = Nothing
        Dim mcMapGroupCursor As MongoCursor = Nothing
        Dim mMapGroup As Trebuchet.MapGroup = Nothing
        Dim bolSave As Boolean = True

        Try

            'Validate Page Data
            ValidateMapGroupData(bolSave)

            If bolSave Then

                'Check to see if the SVGID already exists
                mdDatabase = DBHelper.GetDataBase()
                mcMapGroups = mdDatabase.GetCollection(Of Trebuchet.MapGroup)("MapGroups")

                mcMapGroupCursor = mcMapGroups.FindAs(Of Trebuchet.MapGroup)(Query.And(Query.EQ("Name", txtMapGroupName.Text.Trim)))

                If mcMapGroupCursor.Count > 0 Then

                    bolSave = False

                    'Display Mesage of unique fail

                End If

                If bolSave Then

                    'Save new record
                    mMapGroup = New Trebuchet.MapGroup

                End If

                mMapGroup.Name = txtMapGroupName.Text.Trim
                mMapGroup.Bonus = txtMapGroupBonus.Text.Trim
                mMapGroup.Map_id = Me.CurrentRecord

                mcMapGroups.Save(mMapGroup)

                BindMapGroups()

                'TODO: Not working
                ClearAllControls(divMapGroupAddControls)

            End If

        Catch

        End Try

    End Sub

    Protected Sub ValidateMapGroupData(ByRef bolValid As Boolean)

        Try

            If txtMapGroupName.Text.Trim = "" Then

                bolValid = False

                'Display Message

            End If

            If txtMapGroupBonus.Text.Trim = "" AndAlso Integer.TryParse(txtMapGroupBonus.Text.Trim, 0) Then

                bolValid = False

                'Display Message

            End If

        Catch ex As Exception

        End Try

    End Sub

    Private Sub lvMapGroups_ItemCommand(sender As Object, e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles lvMapGroups.ItemCommand

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcMapGroups As MongoCollection(Of Trebuchet.MapGroup) = Nothing
        Dim mcMapGroupXREF As MongoCollection(Of Trebuchet.MapGroupTerritoryXREF) = Nothing

        Try

            Select Case e.CommandName.ToUpper

                Case "EDITRECORD"
                    'Load the record into modal
                    Me.CurrentMapGroupRecord = ObjectId.Parse(e.CommandArgument)

                    mpeMapGroup.Show()

                    LoadMapGroupModal()

                Case "DELETERECORD"

                    'Delete record
                    mdDatabase = DBHelper.GetDataBase()
                    mcMapGroups = mdDatabase.GetCollection(Of Trebuchet.MapGroup)("MapGroups")
                    mcMapGroupXREF = mdDatabase.GetCollection(Of Trebuchet.MapGroupTerritoryXREF)("MapGroupTerritoryXREF")

                    mcMapGroups.Remove(Query.EQ("_id", ObjectId.Parse(e.CommandArgument)))

                    'Remove all xref records
                    mcMapGroupXREF.Remove(Query.EQ("MapGroup_id", ObjectId.Parse(e.CommandArgument)))

                    'Reload Grid
                    BindMapGroups()

            End Select


        Catch ex As Exception

        End Try

    End Sub

    Private Sub lvMapGroups_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvMapGroups.ItemDataBound

        Try

            If e.Item.ItemType = ListViewItemType.DataItem Then

                CType(e.Item.FindControl("litName"), System.Web.UI.WebControls.Literal).Text = e.Item.DataItem.Name
                CType(e.Item.FindControl("litUnitBonus"), System.Web.UI.WebControls.Literal).Text = e.Item.DataItem.Bonus
                CType(e.Item.FindControl("cmdEdit"), System.Web.UI.WebControls.ImageButton).CommandArgument = e.Item.DataItem._id.ToString
                CType(e.Item.FindControl("cmdDelete"), System.Web.UI.WebControls.ImageButton).CommandArgument = e.Item.DataItem._id.ToString

            End If

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub LoadMapGroupModal()

        Dim mMapGroup As Trebuchet.MapGroup = Nothing

        Try

            mMapGroup = DatabaseCalls.GetMapGroupByID(Me.CurrentMapGroupRecord)

            txtModalMapGroupName.Text = mMapGroup.Name
            txtModalMapGroupBonus.Text = mMapGroup.Bonus

            LoadMapGroupXrefData()

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub LoadMapGroupXrefData()

        Dim mcrMapGroupXrefCursor As MongoCursor = Nothing
        Dim mcrTerritoryCursor As MongoCursor = Nothing
        Dim ttxItem As Trebuchet.Territory = Nothing
        Dim baArray As BsonArray = Nothing

        Try

            'get all data from database
            mcrMapGroupXrefCursor = DatabaseCalls.GetAllTerritoriesFromMapGroupTerritoryXrefByMapGroupID(Me.CurrentMapGroupRecord)

            baArray = New BsonArray()

            For Each ttxItem In mcrMapGroupXrefCursor

                baArray.Add(ttxItem._id)

            Next

            mcrTerritoryCursor = DatabaseCalls.GetAllNonSelectedTerritoriesForXref(baArray)

            lstSelectedGroupTerritories.DataSource = mcrMapGroupXrefCursor
            lstSelectedGroupTerritories.DataValueField = "_id"
            lstSelectedGroupTerritories.DataTextField = "Name"
            lstSelectedGroupTerritories.DataBind()

            lstAvailableGroupTerritories.DataSource = mcrTerritoryCursor
            lstAvailableGroupTerritories.DataValueField = "_id"
            lstAvailableGroupTerritories.DataTextField = "Name"
            lstAvailableGroupTerritories.DataBind()

        Catch ex As Exception


        End Try

    End Sub

    Private Sub cmdMapGroupIn_Click(sender As Object, e As System.EventArgs) Handles cmdMapGroupIn.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcMapGroupXref As MongoCollection(Of Trebuchet.MapGroupTerritoryXREF) = Nothing
        Dim liItem As ListItem = Nothing
        Dim txMapGroupTerritoryXref As Trebuchet.MapGroupTerritoryXREF = Nothing

        Try

            mdDatabase = DBHelper.GetDataBase()
            mcMapGroupXref = mdDatabase.GetCollection(Of Trebuchet.MapGroupTerritoryXREF)("MapGroupTerritoryXREF")

            For Each liItem In lstAvailableGroupTerritories.Items

                If liItem.Selected Then

                    txMapGroupTerritoryXref = New Trebuchet.MapGroupTerritoryXREF()

                    txMapGroupTerritoryXref.MapGroup_id = Me.CurrentMapGroupRecord
                    txMapGroupTerritoryXref.Territory_id = ObjectId.Parse(liItem.Value)

                    mcMapGroupXref.Save(txMapGroupTerritoryXref)

                End If

            Next

            LoadMapGroupXrefData()

        Catch ex As Exception

        End Try

    End Sub

    Private Sub cmdMapGroupOut_Click(sender As Object, e As System.EventArgs) Handles cmdMapGroupOut.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcTerritoryXref As MongoCollection(Of Trebuchet.MapGroupTerritoryXREF) = Nothing
        Dim liItem As ListItem = Nothing

        Try

            mdDatabase = DBHelper.GetDataBase()
            mcTerritoryXref = mdDatabase.GetCollection(Of Trebuchet.MapGroupTerritoryXREF)("MapGroupTerritoryXREF")

            For Each liItem In lstSelectedGroupTerritories.Items

                If liItem.Selected Then

                    mcTerritoryXref.Remove(Query.And(Query.EQ("MapGroup_id", Me.CurrentMapGroupRecord), Query.EQ("Territory_id", ObjectId.Parse(liItem.Value))))

                End If

            Next

            LoadMapGroupXrefData()

        Catch ex As Exception

        End Try

    End Sub

    Private Sub cmdAllMapGroupIn_Click(sender As Object, e As System.EventArgs) Handles cmdAllMapGroupIn.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcTerritoryXref As MongoCollection(Of Trebuchet.MapGroupTerritoryXREF) = Nothing
        Dim liItem As ListItem = Nothing
        Dim txMapGroupTerritoryXref As Trebuchet.MapGroupTerritoryXREF = Nothing

        Try

            mdDatabase = DBHelper.GetDataBase()
            mcTerritoryXref = mdDatabase.GetCollection(Of Trebuchet.MapGroupTerritoryXREF)("MapGroupTerritoryXREF")

            For Each liItem In lstAvailableGroupTerritories.Items

                txMapGroupTerritoryXref = New Trebuchet.MapGroupTerritoryXREF()

                txMapGroupTerritoryXref.MapGroup_id = Me.CurrentMapGroupRecord
                txMapGroupTerritoryXref.Territory_id = ObjectId.Parse(liItem.Value)

                mcTerritoryXref.Save(txMapGroupTerritoryXref)

            Next

            LoadMapGroupXrefData()

        Catch ex As Exception

        End Try

    End Sub

    Private Sub cmdAllMapGroupOut_Click(sender As Object, e As System.EventArgs) Handles cmdAllMapGroupOut.Click

        Dim mdDatabase As MongoDatabase = Nothing
        Dim mcTerritoryXref As MongoCollection(Of Trebuchet.MapGroupTerritoryXREF) = Nothing

        Try

            mdDatabase = DBHelper.GetDataBase()
            mcTerritoryXref = mdDatabase.GetCollection(Of Trebuchet.MapGroupTerritoryXREF)("MapGroupTerritoryXREF")
            mcTerritoryXref.Remove(Query.EQ("MapGroup_id", Me.CurrentMapGroupRecord))

            LoadMapGroupXrefData()

        Catch ex As Exception

        End Try

    End Sub

End Class